﻿
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using System.IO;
using Newtonsoft.Json;

public class AppDataManager : Singleton<AppDataManager>
{

    const string workshopDir = "workshop";

    Dictionary<string, PackageData> dic_id_packageconfig;
    List<PackageData> packageConfigs;
    private string currentPackageID;

    public string CurrentPackageID
    {
        get { return currentPackageID; }
        set
        {
            currentPackageID = value;
        }
    }

    public List<PackageData> PackageDatas
    {
        get { return packageConfigs; }
    }

    public override void Init()
    {
        base.Init();
        dic_id_packageconfig = new Dictionary<string, PackageData>();
        LoadAllAvalablePackagesInfo();
    }

    private void LoadAllAvalablePackagesInfo()
    {
        //扫描包信息
        RefrechPackagesInfo();

        //加载上次打开的包信息
        PackageData lastOpenConfig = null;
        string lastid = AppConfig.Instance.AppConfigData.lastid;
        if (dic_id_packageconfig.ContainsKey(lastid))
        {
            lastOpenConfig = dic_id_packageconfig[lastid];
            Debug.Log("成功加载上次包信息");
        }
        else
        {
            lastOpenConfig = GetDefaultPackageConfig();
        }

        currentPackageID = lastid;
    }

    private void ScanPackageInDir(string dir)
    {
        string[] dirs = Directory.GetDirectories(dir);
        if (dirs.Length > 0)
        {
            for (int i = 0; i < dirs.Length; i++)
            {
                string packageName = dirs[i];
                string configpath = Path.Combine(packageName, "config.json");
                PackageData tempconfig = LoadPackageConfig(configpath);
                if (tempconfig != null)
                {
                    if (!dic_id_packageconfig.ContainsKey(tempconfig.packageConfig.id))
                    {
                        dic_id_packageconfig.Add(tempconfig.packageConfig.id, tempconfig);
                    }
                }
            }
        }
    }

    public PackageData GetPackageInfo(string id)
    {
        if (dic_id_packageconfig.ContainsKey(id))
        {
            return dic_id_packageconfig[id];
        }
        return null;
    }

    public PackageData GetCurrentPackageInfo()
    {
        if (dic_id_packageconfig.ContainsKey(CurrentPackageID))
        {
            return dic_id_packageconfig[CurrentPackageID];
        }
        return null;
    }


    public void RefrechPackagesInfo()
    {
        string defaultPackageDir = Path.Combine(Application.streamingAssetsPath, "packages");
        string wsDir = workshopDir;
        ScanPackageInDir(defaultPackageDir);
        ScanPackageInDir(wsDir);
        packageConfigs = dic_id_packageconfig.Values.ToList();
    }

    public void SaveCurrentPackageInfo()
    {
        PackageData packageData = GetPackageInfo(this.CurrentPackageID);
        string jsonStr = JsonConvert.SerializeObject(packageData.packageConfig, Formatting.Indented);
        string jsonPath = Path.Combine(packageData.packageDir, "config.json");
        File.WriteAllText(jsonPath, jsonStr);
    }

    private PackageData LoadPackageConfig(string tempfilename)
    {
        if (File.Exists(tempfilename))
        {
            string configStr = File.ReadAllText(tempfilename);
            PackageConfig config = JsonConvert.DeserializeObject<PackageConfig>(configStr);
            return new PackageData() { packageDir = Path.GetDirectoryName(tempfilename), packageConfig = config };
        }
        return null;
    }

    public PackageData GetDefaultPackageConfig()
    {
        PackageConfig packageConfig = new PackageConfig()
        {
            id = "test",
            name = "girls",
            winScalePercent = 0.4f,
            PosX = 0.4f,
            PosY = 0.4f,
            winAlpha = 255,
            winStyle = enumWinStyle.WinTopAphaPenetrate,
            changeMode = PaperManager.ItemChangeMode.Stanby,
            checkMode = PaperManager.CheckMode.WindowArea,
            fadeInType = PaperManager.FadeInType.SimpleFlyIn,
            fadeOutType = PaperManager.FadeOutType.SimpleFlyOut,
            changeDur = 15,
            effecttype = EffectMgr.EffectType.simple_particles,
            isSupportAudioVisual = true,
            audioVisulStrengh = 1,
            isTransparentWhenHover = true,
            isWinAutoActive = false,
            winAspectHW = 0.75f,
            scaling_tolerance = 10,
            camera_offsetX = 0,
            camera_offsetY = 1,
            focus_effect = true
           
        };
        string dir = Path.Combine(new string[] { Application.streamingAssetsPath, "packages", packageConfig.id });
        return new PackageData() { packageConfig = packageConfig, packageDir = dir };
    }

}

public class PackageData
{
    public string packageDir;
    public PackageConfig packageConfig;
}

public class PackageConfig
{
    public string id;
    public string name;
    //资源类型：普通媒体资源或ab包
    public PaperManager.AssetType assetType;
    public PaperManager.Catagory catagory;
    public int winAlpha;
    public float winScalePercent;
    public float winAspectHW = 0.75f;
    public float PosX;
    public float PosY;
    public enumWinStyle winStyle;
    //图片切换的方式（列表，随机）
    public PaperManager.ItemChangeMode changeMode;
    //鼠标检测模式（分为窗口，精确，非常精确）
    public PaperManager.CheckMode checkMode;
    //图片切入方式
    public PaperManager.FadeInType fadeInType;
    //图片切出方式
    public PaperManager.FadeOutType fadeOutType;
    //图片切换间隔
    public float changeDur;
    //鼠标滑过时是否透明
    public bool isTransparentWhenHover;
    //是否支持音频可视化
    public bool isSupportAudioVisual;
    //音频可视化强度
    public float audioVisulStrengh;
    //特效类型
    public EffectMgr.EffectType effecttype;
    //窗口是否自动激活
    public bool isWinAutoActive;
    //缩放容忍度
    public float scaling_tolerance;
    //相机横向偏移值
    public float camera_offsetX;
    //相机纵向偏移值
    public float camera_offsetY;
    //是否开启focus效果
    public bool focus_effect;
}
